package concurrency.multithreading;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-03-14 14:19
 **/
public class UserThreadFactory implements ThreadFactory {
    private final String namePrefix;
    private final AtomicInteger nextId = new AtomicInteger();

    // 定义线程组名称,对于使用jstack排查时非常有用
    public UserThreadFactory(String whatFeatureOfGroup) {
        namePrefix = "UserThreadFactory'S " + whatFeatureOfGroup + "-Worker-";
    }

    @Override
    public Thread newThread(Runnable r) {
        String name = namePrefix + nextId.getAndIncrement();
        Thread thread = new Thread(null, r, name, 0);
        System.out.println(thread.getName());
        return null;
    }
}

// 任务执行体
class Task implements Runnable {
    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public void run() {
        System.out.println("Running " + count.getAndIncrement());
    }
}
